package com.tanjie.blackbean.iot.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author tanjie
 * @Date 2022/6/20 下午4:02 周一
 **/
@Configuration
@Slf4j
public class MqttConfiguration {

    public static String broker = "tcp://192.168.2.5:31883";

    public static String clientId = "blackbean-mqtt-client";

    @Bean
    public MqttClient mqttClient() {
        try {
            MemoryPersistence persistence = new MemoryPersistence();
            MqttClient client = new MqttClient(broker, clientId, persistence);
            // MQTT 连接选项
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setUserName("appuser");
            connOpts.setPassword("app123".toCharArray());
            // 保留会话
            connOpts.setCleanSession(true);
            // 建立连接
            client.connect(connOpts);
            return client;
        } catch (MqttException me) {
            log.error("创建mqttClient实例失败，cause: {}", me.getMessage());
            return null;
        }
    }

}
